package ru.papergames.model.proxies
{
	import mx.rpc.IResponder;
	
	import org.puremvc.as3.interfaces.IFacade;
	
	import ru.papergames.controller.notifications.CoreNotifications;
	import ru.papergames.model.proxies.HTTPProxy;
	import ru.papergames.model.vo.PopupMessageVO;
	import ru.papergames.controller.notifications.FrontendNotifications;
	
	import system.events.Delegate;

	public class MainHTTPProxy extends HTTPProxy
	{				
		
		public static var topFacade:IFacade;
		
		private static const MESSAGES_NOTE_TYPES:Object = {
							message: 	CoreNotifications.SYS_MESSAGE, 
							error: 		CoreNotifications.SYS_ERROR, 
							exception: 	CoreNotifications.SYS_SERVER_EXCEPTION,
							warning: 	CoreNotifications.SYS_WARNING};
		
		private static const MESSAGES_NOTE_LABELS:Object = {
							message: 	'Сообщение', 
							error: 		'Ошибка', 
							exception: 	'Исключение сервера',
							warning: 	'Предупреждение'};
		
		
		private static var INSTANCES:Array = [];		
		
		protected var useOperationParam:Boolean = true;
		protected var shareResponse:Boolean = true;
		
		protected var lastRequest:Function;
		public var lastMethod:String;
		
		public function MainHTTPProxy(pName:String, url:String, data:Object, timeout:int = 0)
		{
			super(pName, url, data, timeout);
		}
		
		override public function onRegister():void {
			super.onRegister();
			INSTANCES.push(this);
		}
		
		override public function onRemove():void {
			super.onRemove();
			
			for (var i:* in INSTANCES) {
				if (INSTANCES[i] == this) {
					delete INSTANCES[i];
					break;
				}
			}			
		}
				
		override public function call(method:String, params:Object=null):void {
			
			lastRequest = Delegate.create(this, call, method, params);
			lastMethod = method;
			
			if (useOperationParam) {			
				if (params) {
					params.operation = method;
				} else {
					params = {operation: method};
				}			
			}
			
			super.call(method, params);
		}
		
		public function repeatLastRequest():void {
			if (lastRequest is Function) lastRequest();
		}
		
		override protected function getResponderForMethod(method:String):IResponder {
			//gets function for responding
			var resp:MainResponder = new MainResponder(this.facade, method + SUCCESS_NOTE_POSTFIX, 
													   method + FAULT_NOTE_POSTFIX,
													   COMPLETE);
			
 			var resultFunction:String = method + '_Result';
			var faultFunction:String = method + '_Fault';
			
			resp.mainResultFunction = mainResult;
			resp.invokerProxy = this;
			
			resp.method = method;
								 
			try {
				
				if ( method.search(/^[0-9]+$/) != -1 ) {
					
					resp.resultFunction = this['_' + resultFunction];
					
				} else {
					resp.resultFunction = this[resultFunction];
				}
				
			} catch (e:Error) {
				//logger.warn('Result handler "' + resultFunction + '" is missing. Default invoked');
				resp.resultFunction = generic_Result;
			}
			 
			try {
				
				resp.faultFunction = this[faultFunction];
				
			} catch (e:Error) {
				//logger.info('Fault handler "' + faultFunction + '" is missing. Default invoked');
				resp.faultFunction = generic_Fault;
			}
			 
			return resp;		
		}
		
				
		public static function mainResult(data:XML, invokerProxy:MainHTTPProxy = null):void {
			//let data to be parsed by all instances before theirs specific handling
			if (!invokerProxy || (invokerProxy && invokerProxy.shareResponse)) {
				
				for each (var proxy:MainHTTPProxy in INSTANCES) {
					if (proxy.shareResponse) proxy.parseResponse(data, invokerProxy == proxy);
				}
				
			} else if (invokerProxy && !invokerProxy.shareResponse) {
				
				invokerProxy.parseResponse(data, true);
				
			}
			
			//parse messages tag if any
			for each (var msg:* in data.messages.message) {
				var noteType:String = MESSAGES_NOTE_TYPES[msg.@type];
				var popupTitle:String = MESSAGES_NOTE_LABELS[msg.@type];
				noteType = noteType ? noteType : CoreNotifications.SYS_MESSAGE;
				popupTitle = popupTitle ? popupTitle : MESSAGES_NOTE_LABELS.message;
				var popupMsg:PopupMessageVO = new PopupMessageVO(msg.toString(), popupTitle, false);
				//if ( String(msg.@imageId) ) popupMsg.image = ImagesPathHelper.getImagePath(msg.@imageId);
				topFacade.sendNotification(noteType, popupMsg );
			}
			
			//check forced logout
			if (data.data.forceLogout.toString() == 'true') {
				//topFacade.sendNotification(FrontendNotifications.LOGOUT);
				//topFacade.sendNotification(FrontendNotifications.SERVER_RESTARTING);
			} 
		}
		
		/**
		 * Parses data packet by finding info needed for the proxy
		 * 
		 * */
		protected function parseResponse(data:XML, ownResponse:Boolean):void {
			if (this.shareResponse) 
				throw new Error('parseResponse should be overriden (shareResponse=true)!!!');
		}
		
	}
}